/* eslint-disable no-useless-catch */
import DrawerFooter from '@/components/DrawerFooter';
import { Button, Dialog } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React from 'react';

const FormFooter = (props) => {
  const {
    onCancel,
    current,
    handleSetCurrent,
    onSubmit,
    totalStep,
    stepFunc,
  } = props;

  const goBackStep = async () => {
    handleSetCurrent((cur) => cur - 1);
  };

  const showDialog = (type, message, onOk) => {
    const dialogMethod = type === 'warning' ? Dialog.warning : Dialog.error;
    dialogMethod({
      content: t`${message}`,
      onOk,
    });
  };

  const goNextStep = async () => {
    try {
      await stepFunc();
      handleSetCurrent((cur) => cur + 1);
    } catch (error) {
      const { type = 'error', message = error } = error;
      showDialog(type, message, () => handleSetCurrent((cur) => cur + 1));
    }
  };

  const BUTTON_SETTING = {
    CANCEL: <Button key="cancel" onClick={onCancel} style={{ margin: '0 2px' }}>取消</Button>,
    BACK: <Button key="back" type="primary" onClick={goBackStep} style={{ margin: '0 2px' }}>上一步</Button>,
    NEXT: <Button key="next" type="primary" onClick={goNextStep} style={{ margin: '0 2px' }}>下一步</Button>,
    SUBMIT: <Button key="submit" type="primary" onClick={() => onSubmit()} style={{ margin: '0 2px' }}>提交</Button>,
  };

  const getFooterDom = () => {
    const { CANCEL, BACK, NEXT, SUBMIT } = BUTTON_SETTING;
    let footerDom = [CANCEL, NEXT];
    if (current === totalStep - 1) {
      footerDom = [BACK, SUBMIT];
    } else if (current !== 0) {
      footerDom = [BACK, NEXT];
    }
    return footerDom;
  };

  return (
    <DrawerFooter>
      {getFooterDom()}
    </DrawerFooter>
  );
};

export default observer(FormFooter);
